<template>
  <div class="property-detail-container">
    <!-- 返回按钮 -->
    <div class="back-button" @click="goBack">
      <i class="el-icon-arrow-left"></i>
      <span>返回</span>
    </div>

    <!-- 房源基本信息 -->
    <div class="property-basic">
      <div class="property-title-section">
        <h1 class="property-title">
          {{
            propertyData.propertyName || propertyData.sourceName || "房源详情"
          }}
        </h1>
        <div class="property-tags">
          <span v-for="tag in propertyTags" :key="tag" class="tag">{{
            tag
          }}</span>
        </div>
      </div>

      <div class="property-images">
        <el-carousel height="400px" indicator-position="outside">
          <el-carousel-item
            v-for="(image, index) in propertyImages"
            :key="index"
          >
            <img
              :src="image"
              :alt="propertyData.propertyName"
              class="carousel-image"
            />
          </el-carousel-item>
        </el-carousel>
      </div>

      <div class="property-price-section">
        <div class="price-info">
          <span class="total-price"
            >¥{{
              formatPrice(
                propertyData.totalPrice || propertyData.houseTotalPrice || 0
              )
            }}</span
          >
          <span class="unit-price"
            >均价
            {{
              formatPrice(
                propertyData.averagePrice || propertyData.unitPrice || 0
              )
            }}/㎡</span
          >
        </div>
        <div class="discount" v-if="propertyData.discount">
          {{ propertyData.discount }}
        </div>
      </div>
    </div>

    <!-- 房源详细信息 -->
    <div class="property-details">
      <div class="detail-section">
        <h2 class="section-title">房源信息</h2>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="label"><i class="el-icon-tickets"></i> 房源编号</span>
            <span class="value">{{
              propertyData.propertyId || propertyData.sourceId || "未知"
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-menu"></i> 房源类型</span>
            <span class="value">{{ propertyData.typeName || "住宅" }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-home"></i> 户型</span>
            <span class="value">{{ propertyData.houseType || "未知" }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-s-grid"></i> 建筑面积</span>
            <span class="value"
              >{{
                formatArea(
                  propertyData.buildingArea ||
                    propertyData.houseBuildingArea ||
                    0
                )
              }}㎡</span
            >
          </div>
          <div class="detail-item">
            <span class="label"
              ><i class="el-icon-location-arrow"></i> 朝向</span
            >
            <span class="value">{{ propertyData.orientation || "未知" }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-sort"></i> 楼层</span>
            <span class="value">{{ propertyData.floorInfo || "未知" }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-brush"></i> 装修情况</span>
            <span class="value">{{
              propertyData.decorationName || "未知"
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label"
              ><i class="el-icon-circle-check"></i> 房源状态</span
            >
            <span class="value">{{ propertyData.statusName || "在售" }}</span>
          </div>
        </div>
      </div>

      <!-- 小区信息 -->
      <div class="detail-section">
        <h2 class="section-title">小区信息</h2>
        <div class="detail-grid">
          <div class="detail-item">
            <span class="label"><i class="el-icon-building"></i> 小区名称</span>
            <span class="value">{{
              propertyData.communityName || "未知"
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label"
              ><i class="el-icon-map-marker"></i> 所在区域</span
            >
            <span class="value">{{ propertyData.areaName || "未知" }}</span>
          </div>
          <div class="detail-item">
            <span class="label"
              ><i class="el-icon-location-outline"></i> 小区地址</span
            >
            <span class="value">{{
              propertyData.communityAddress || propertyData.address || "未知"
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-date"></i> 建成年份</span>
            <span class="value">{{
              formatYear(
                propertyData.constructionYear ||
                  propertyData.constructionYears ||
                  "未知"
              )
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-cpu"></i> 开发商</span>
            <span class="value">{{ propertyData.developer || "未知" }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-service"></i> 物业公司</span>
            <span class="value">{{
              propertyData.propertyCompany || "暂无资料"
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label"><i class="el-icon-money"></i> 物业费</span>
            <span class="value">{{
              propertyData.propertyFee
                ? propertyData.propertyFee + "元/㎡·月"
                : "暂无资料"
            }}</span>
          </div>
          <div class="detail-item">
            <span class="label"
              ><i class="el-icon-hourglass"></i> 产权年限</span
            >
            <span class="value">{{
              propertyData.propertyRightYear
                ? propertyData.propertyRightYear + "年"
                : "暂无资料"
            }}</span>
          </div>
        </div>
      </div>

      <!-- 特色信息 -->
      <div class="detail-section" v-if="hasSpecialFeatures">
        <h2 class="section-title">房源特色</h2>
        <div class="features-list">
          <span class="feature-tag" v-if="propertyData.isExclusive === 1"
            >独家房源</span
          >
          <span class="feature-tag" v-if="propertyData.isLowDensity === 1"
            >低密度</span
          >
          <span
            class="feature-tag"
            v-if="propertyData.isUnderConstruction === 1"
            >在建</span
          >
          <span class="feature-tag" v-if="propertyData.openingDate"
            >开盘时间: {{ formatDate(propertyData.openingDate) }}</span
          >
        </div>
      </div>

      <!-- 房源描述 -->
      <div class="detail-section" v-if="propertyData.sourceIntro">
        <h2 class="section-title">房源描述</h2>
        <div class="property-description">
          {{ propertyData.sourceIntro }}
        </div>
      </div>

      <!-- 看房按钮 -->
      <div class="action-buttons">
        <el-button type="primary" size="large" class="view-button">
          <i class="el-icon-view"></i>
          预约看房
        </el-button>
        <el-button type="info" size="large" class="call-button">
          <i class="el-icon-phone"></i>
          电话咨询
        </el-button>
        <el-button
          type="success"
          size="large"
          class="service-button"
          @click="openCustomerService"
        >
          <i class="el-icon-chat-line-square"></i>
          在线客服
        </el-button>
      </div>
    </div>

    <!-- 悬浮客服按钮 -->
    <div class="float-service-button" @click="openCustomerService">
      <i class="el-icon-chat-dot-round"></i>
      <span class="service-text">在线客服</span>
    </div>

    <!-- 客服聊天弹窗 -->
    <div class="customer-service-modal" v-if="showCustomerService">
      <div class="modal-header">
        <div class="header-info">
          <img
            src="https://via.placeholder.com/40"
            alt="客服头像"
            class="service-avatar"
          />
          <div class="service-info">
            <h3>房产顾问</h3>
            <span class="online-status"
              ><i class="el-icon-circle-check"></i> 在线</span
            >
          </div>
        </div>
        <button class="close-button" @click="closeCustomerService">
          <i class="el-icon-close"></i>
        </button>
      </div>
      <div class="chat-messages">
        <div class="system-message">
          您好，很高兴为您服务！请问有什么可以帮助您的？
        </div>
        <div
          v-for="(msg, index) in chatMessages"
          :key="index"
          :class="['message', msg.sender]"
        >
          <div class="message-content">
            {{ msg.content }}
          </div>
          <div class="message-time">
            {{ formatMessageTime(msg.time) }}
          </div>
        </div>
      </div>
      <div class="chat-input">
        <textarea
          v-model="inputMessage"
          placeholder="请输入您的问题..."
          @keydown.enter.ctrl="sendMessage"
        ></textarea>
        <button
          class="send-button"
          @click="sendMessage"
          :disabled="!inputMessage.trim()"
        >
          发送
        </button>
      </div>
    </div>

    <!-- 遮罩层 -->
    <div
      class="modal-overlay"
      v-if="showCustomerService"
      @click="closeCustomerService"
    ></div>

    <!-- 加载中状态 -->
    <div class="loading-container" v-if="loading">
      <el-loading-spinner></el-loading-spinner>
      <p>加载中...</p>
    </div>

    <!-- 错误提示 -->
    <div class="error-container" v-if="error">
      <i class="el-icon-error"></i>
      <p>{{ error }}</p>
      <el-button type="primary" @click="loadPropertyDetail">重新加载</el-button>
    </div>
  </div>
</template>

<script>
import { getcommunityType } from "@/api/houses.js";

export default {
  name: "PropertyDetail",
  data() {
    return {
      propertyData: {},
      loading: true,
      error: "",
      propertyImages: [
        "https://images.unsplash.com/photo-1560448204-e02f11c3d0e2?w=800&h=600&fit=crop",
        "https://images.unsplash.com/photo-1502672260266-1c1ef2d93688?w=800&h=600&fit=crop",
        "https://images.unsplash.com/photo-1493809842364-78817add7ffb?w=800&h=600&fit=crop",
      ],
      showCustomerService: false,
      chatMessages: [],
      inputMessage: "",
    };
  },
  computed: {
    propertyTags() {
      const tags = [];
      if (this.propertyData.isExclusive === 1) tags.push("独家房源");
      if (this.propertyData.isLowDensity === 1) tags.push("低密度");
      if (this.propertyData.isUnderConstruction === 1) tags.push("在建");
      if (this.propertyData.decorationName)
        tags.push(this.propertyData.decorationName);
      if (tags.length === 0) tags.push("推荐房源");
      return tags;
    },
    hasSpecialFeatures() {
      return (
        this.propertyData.isExclusive === 1 ||
        this.propertyData.isLowDensity === 1 ||
        this.propertyData.isUnderConstruction === 1 ||
        this.propertyData.openingDate
      );
    },
  },
  mounted() {
    this.loadPropertyDetail();
  },
  methods: {
    loadPropertyDetail() {
      const sourceId = this.$route.params.id;
      if (!sourceId) {
        this.error = "无效的房源ID";
        this.loading = false;
        return;
      }

      this.loading = true;
      this.error = "";

      getcommunityType(sourceId)
        .then((res) => {
          this.loading = false;
          if (res.code === 200 && res.data) {
            this.propertyData = res.data;
            // 如果有更多图片，可以在这里添加
            if (res.data.images && Array.isArray(res.data.images)) {
              this.propertyImages = res.data.images;
            }
          } else {
            this.error = "获取房源详情失败";
            console.error("获取房源详情失败:", res);
          }
        })
        .catch((err) => {
          this.loading = false;
          this.error = "网络错误，请稍后重试";
          console.error("获取房源详情异常:", err);
        });
    },
    formatPrice(price) {
      if (typeof price === "number") {
        return price.toLocaleString("zh-CN");
      }
      return "0";
    },
    formatArea(area) {
      if (typeof area === "number") {
        return area.toFixed(2);
      }
      return "0.00";
    },
    formatDate(dateStr) {
      try {
        const date = new Date(dateStr);
        return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(
          2,
          "0"
        )}-${String(date.getDate()).padStart(2, "0")}`;
      } catch (error) {
        return dateStr;
      }
    },
    formatYear(yearStr) {
      try {
        if (typeof yearStr === "string" && yearStr.includes("-")) {
          return yearStr.split("-")[0];
        }
        return yearStr;
      } catch (error) {
        return yearStr;
      }
    },
    goBack() {
      this.$router.go(-1);
    },

    // 客服相关方法
    openCustomerService() {
      this.showCustomerService = true;
      // 重置聊天记录
      this.chatMessages = [];
      this.inputMessage = "";
      // 自动滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });
    },

    closeCustomerService() {
      this.showCustomerService = false;
    },

    sendMessage() {
      const message = this.inputMessage.trim();
      if (!message) return;

      // 添加用户消息
      this.chatMessages.push({
        content: message,
        sender: "user",
        time: new Date(),
      });

      this.inputMessage = "";

      // 自动滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom();
      });

      // 模拟客服回复
      setTimeout(() => {
        this.chatMessages.push({
          content:
            "感谢您的咨询，我已记录您的问题，稍后会为您提供更详细的解答。",
          sender: "service",
          time: new Date(),
        });
        // 自动滚动到底部
        this.$nextTick(() => {
          this.scrollToBottom();
        });
      }, 1000);
    },

    scrollToBottom() {
      const chatContainer = document.querySelector(".chat-messages");
      if (chatContainer) {
        chatContainer.scrollTop = chatContainer.scrollHeight;
      }
    },

    formatMessageTime(date) {
      const d = new Date(date);
      const hours = String(d.getHours()).padStart(2, "0");
      const minutes = String(d.getMinutes()).padStart(2, "0");
      return `${hours}:${minutes}`;
    },
  },
};
</script>

<style scoped>
.property-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40px;
}

.back-button {
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 100;
  background: rgba(255, 255, 255, 0.9);
  padding: 8px 12px;
  border-radius: 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.back-button:hover {
  background: white;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.property-basic {
  background: white;
  padding: 20px;
  margin-bottom: 20px;
}

.property-title-section {
  margin-bottom: 20px;
}

.property-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 12px;
  color: #333;
}

.property-tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.tag {
  background: #e8f4fd;
  color: #1890ff;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 12px;
}

.property-images {
  margin-bottom: 20px;
}

.carousel-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.property-price-section {
  background: #fff7e6;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.price-info {
  flex: 1;
}

.total-price {
  font-size: 32px;
  font-weight: bold;
  color: #ff4d4f;
  margin-right: 12px;
}

.unit-price {
  font-size: 16px;
  color: #666;
}

.discount {
  background: #ff4d4f;
  color: white;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
}

.property-details {
  background: white;
  padding: 20px;
}

.detail-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  color: #333;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 2px solid #f0f0f0;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.detail-item:last-child {
  border-bottom: none;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.features-list {
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
  padding: 12px 0;
}

.feature-tag {
  background: #f6ffed;
  color: #52c41a;
  padding: 6px 16px;
  border-radius: 20px;
  font-size: 14px;
  border: 1px solid #b7eb8f;
}

.property-description {
  line-height: 1.8;
  color: #333;
  font-size: 15px;
  padding: 12px 0;
}

.action-buttons {
  display: flex;
  gap: 16px;
  margin-top: 30px;
}

.view-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
}

.call-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
}

.service-button {
  flex: 1;
  height: 50px;
  font-size: 16px;
}

/* 悬浮客服按钮 */
.float-service-button {
  position: fixed;
  bottom: 60px;
  right: 40px;
  background: #1890ff;
  color: white;
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
  transition: all 0.3s ease;
  z-index: 100;
}

.float-service-button:hover {
  background: #40a9ff;
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.5);
}

.float-service-button i {
  font-size: 24px;
  margin-bottom: 4px;
}

.service-text {
  font-size: 10px;
  white-space: nowrap;
}

/* 客服聊天弹窗 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 200;
  display: flex;
  align-items: center;
  justify-content: center;
}

.customer-service-modal {
  position: fixed;
  right: 40px;
  bottom: 140px;
  width: 400px;
  height: 500px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
  display: flex;
  flex-direction: column;
  z-index: 201;
}

.modal-header {
  padding: 16px 20px;
  background: #f0f2f5;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 8px 8px 0 0;
}

.header-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.service-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
}

.service-info h3 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.online-status {
  font-size: 12px;
  color: #52c41a;
}

.close-button {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #666;
  padding: 4px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-button:hover {
  background: #e8e8e8;
  color: #333;
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #fafafa;
}

.system-message {
  text-align: center;
  color: #999;
  font-size: 12px;
  margin-bottom: 20px;
  padding: 4px 12px;
  background: #e8e8e8;
  border-radius: 16px;
  display: inline-block;
}

.message {
  margin-bottom: 16px;
  display: flex;
  flex-direction: column;
}

.message.user {
  align-items: flex-end;
}

.message.service {
  align-items: flex-start;
}

.message-content {
  max-width: 70%;
  padding: 10px 14px;
  border-radius: 12px;
  word-wrap: break-word;
  line-height: 1.5;
}

.message.user .message-content {
  background: #1890ff;
  color: white;
  border-bottom-right-radius: 4px;
}

.message.service .message-content {
  background: white;
  color: #333;
  border: 1px solid #e8e8e8;
  border-bottom-left-radius: 4px;
}

.message-time {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
}

.chat-input {
  padding: 16px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.chat-input textarea {
  width: 100%;
  height: 80px;
  padding: 10px;
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  resize: none;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s ease;
}

.chat-input textarea:focus {
  border-color: #1890ff;
}

.send-button {
  align-self: flex-end;
  padding: 8px 20px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.3s ease;
}

.send-button:hover:not(:disabled) {
  background: #40a9ff;
}

.send-button:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #666;
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400px;
  color: #ff4d4f;
}

.error-container i {
  font-size: 48px;
  margin-bottom: 16px;
}

.error-container p {
  margin-bottom: 20px;
  font-size: 16px;
}
</style>
